import { Body, Controller, Get, Post, Put, Query, Req ,Delete, Param} from '@nestjs/common';
import { ApiBearerAuth, ApiBody, ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
import { MenuService } from './menu.service';
import { MenuWithChildrenDto, PageMenuDto } from '../../dto/menu/menu.dto';

import { PaginatedResponseDto } from '../../common/class/res.class';
import { PageOptionsDto } from '../../dto/page.dto';
import { Menu } from '../../entities/menu.entity';

@ApiTags('菜单管理')
@ApiBearerAuth()
@Controller('menu')
export class MenuController {
  constructor(private readonly menuService: MenuService) {}
  @ApiOperation({ summary: '查询所有菜单' })
  @Get('tree')
  @ApiOkResponse({ type: MenuWithChildrenDto, description: '查询所有菜单' })
  async getMenuTree(): Promise<MenuWithChildrenDto[]> {
    const flatMenus = await this.menuService.getAllMenus(); // 替换为获取所有菜单的方法
    console.log(flatMenus,'flatMenus');
    
    const menuTree = this.menuService.buildMenuTree(flatMenus);
    return menuTree;
  }
  @ApiOperation({ summary: '新增菜单信息' })
  @Post()
  @ApiBody({type:Menu,description:"输入菜单信息"})
  async createPost(
    @Req() req: Request,
    @Body() createInput: Menu | any,
  ): Promise<any> {
    await this.menuService.create(createInput);
    return '新增成功';
  }
   // 更新菜单
   @ApiOperation({ summary: '新增更新菜单' })
   @Put()
   async updateMenu(@Body() updateMenuDto: Menu): Promise<Menu> {
     return this.menuService.updateMenu(updateMenuDto.id,updateMenuDto);
   }
 
   // 删除菜单
   @ApiOperation({ summary: '删除菜单' })
   @Delete(':id')
   async deleteMenu(@Param('id') id: string): Promise<void> {
     return this.menuService.deleteMenu(id);
   }
   @ApiOperation({ summary: '分页条件查询菜单' })
  @Get('page')
  @ApiOkResponse({ type: PaginatedResponseDto<MenuWithChildrenDto>, description: '分页条件查询菜单' })
  async page(
    @Query() dto: PageMenuDto,
  ): Promise<PaginatedResponseDto<MenuWithChildrenDto>> {
    const [records, total] = await this.menuService.getMenusWithPageOptions(
      dto,
    );
    return {
      msg: '查询成功',
      data: {
      records,
      pageSize: dto.pageSize,
      pageNo: dto.pageNo,
      total,
      },
    };
  
  }
}
